import * as React from 'react'
import { Input, Form, Button,message, Upload } from 'antd'
import { Config, User } from '../../serve/interface';
import { RcFile, UploadChangeParam } from 'antd/lib/upload';
import { avatarUpdate } from '../api';
import { UploadFile } from 'antd/lib/upload/interface';
declare var __all_config__: Partial<Config>;
const { store } = __all_config__

const FormItem = Form.Item

export interface UserCenterProps {
    user?: User
    changePassword?: ({ pw0, pw1, pw2 }) => Promise<void>
}

export interface UserCenterState {
    isEditNickName: boolean
    nickName: string
    nickNameError: string
    pw0: string
    pw1: string
    pw2: string
    pwError: string
    avatarUrl: string
}

class UserCenter extends React.Component<UserCenterProps, UserCenterState>{
    constructor(props: UserCenterProps) {
        super(props)
        this.state = {
            isEditNickName: false,
            nickName: '',
            nickNameError: '',
            pw0: '',
            pw1: '',
            pw2: '',
            pwError: '',
            avatarUrl: `/${__all_config__.admin_url}/avatar?username=${props.user.name}`,
        }

    }
    onChangeFile = ({file}: UploadChangeParam<UploadFile<any>>) => {
        if (file.status != 'done') {
            return
        }
        if (file.size > __all_config__.avatar_size) {
            message.error('图片大小不要超过100K')
            return
        }
        const t = this
        const reader = new FileReader()
        reader.addEventListener('load', function () {
            avatarUpdate({ avatar: reader.result })
            .then(function () {
                t.setState({
                    avatarUrl: `/${__all_config__.admin_url}/avatar?username=${t.props.user.name}&t=${Date.now()}`,
                })
            })
        })
        reader.addEventListener('error', function (err) {
            message.error(err)
        })
        reader.readAsDataURL(file.originFileObj)
    }
    render() {
        const { user } = this.props;
        const { pw0, pw1, pw2, pwError } = this.state;
        const formItemLayout = {
            labelCol: { span: 2 },
            wrapperCol: { span: 6 },
        };

        return <Form onFinish={this.changePassword}>
            <FormItem
                label="用户名"
                {...formItemLayout}
            >
                <p style={{ margin: 0 }}>{user ? user['name'] : ''}</p>
            </FormItem>
            <FormItem
                label="昵称"
                {...formItemLayout}
            >
                <p style={{ margin: 0 }}>{user ? user['nickname'] : ''}</p>
            </FormItem>

            {__all_config__.use_avatar && <FormItem {...formItemLayout} label="头像">
                <Upload name="avatar" listType="picture-card" showUploadList={false} accept="image/*" onChange={this.onChangeFile}>
                    <img src={this.state.avatarUrl} alt="avatar" style={{ width: '100%' }}/>
                </Upload>
            </FormItem>}

            {store.usePasswordChange && <React.Fragment>
                <FormItem {...formItemLayout} label="原始密码" required>
                    <Input name="pw0" type="password" placeholder="原始密码" value={pw0} onChange={(e) => this.updateValue(e, 'pw0')} required />
                </FormItem>

                <FormItem {...formItemLayout} label="新密码" required>
                    <Input name="pw1" type="password" maxLength={16} placeholder="长度8-16位，需包含大小写字母及数字" value={pw1} onChange={(e) => this.updateValue(e, 'pw1')} required />
                </FormItem>

                <FormItem {...formItemLayout} label="确认密码" required>
                    <Input name="pw2" type="password"maxLength={16}  placeholder="长度8-16位，需包含大小写字母及数字" value={pw2} onChange={(e) => this.updateValue(e, 'pw2')} required />
                </FormItem>
                <p>{pwError}</p>

                <FormItem
                    wrapperCol={{ span: 12, offset: 7 }}
                >
                    <Button type="primary" onClick={this.changePassword}>确定</Button>
                </FormItem>
            </React.Fragment>}
        </Form>
    }

    updateEditNickNameStatus = (isEdit: boolean) => {
        let nickname = isEdit ? this.props.user.nickname : '';
        this.setState({
            isEditNickName: isEdit,
            nickName: nickname
        });
    }

    changePassword = (e) => {
        e.preventDefault();
        const { pw0, pw1, pw2 } = this.state;
        this.props.changePassword({
            pw0,
            pw1,
            pw2
        }).then(data => {
            if (data['error']) {
                message.warning(data['error']);
            } else {
                message.info('修改成功');
                this.setState({
                    pw0: '',
                    pw1: '',
                    pw2: ''
                })
            }
        });
        return false;
    }

    updateValue = (e, prop: keyof UserCenterState) => {
        var value: any = e.currentTarget.value.replace(/(^\s*)|(\s*$)/g, "")
        this.setState({
            [prop]: value,
        } as any);
    }
}

export default UserCenter